/**
 * @Author: liutao
 * @Date:   2017-03-15T11:27:54+08:00
 * @Email:  947809647@qq.com
 * @Last modified by:   liutao
 * @Last modified time: 2017-03-21T10:10:20+08:00
 */

import { showMsg, getMenuList } from '../../vuex/action'
import session from '../../util/session.js'

export default {
  name: 'Menu',
  data() {
    return {
      menuTop: '',
      uid: '',
      scrollBottom: 50,
      isShowMenu: true,
      activeNode: [],
      activeLeaf: null
    }
  },
  computed: {
    sortMenuList() {
      let sortMenuList = []
      if (this.menuList && this.menuList.length > 0) {
        sortMenuList = this.menuList.sort((a, b) => {
          return a.sort - b.sort
        })
      }
      return sortMenuList
    }
  },
  methods: {
    nodeCheck(id, isLeaf) {
      let node = this.activeNode
      let leaf = this.activeLeaf
      return (
        (isLeaf && leaf && id === leaf) || (!isLeaf && node && node.length && node.indexOf(id) > -1)
      )
    },
    nodeClass(id, isLeaf) {
      return (isLeaf ? 'leaf' : 'node') + ' ' + (this.nodeCheck(id, isLeaf) ? 'active' : '')
    },
    toogleNode(...args) {
      let prev = this.activeNode
      if (args.length === 2 && args[0] === prev[0] && args[1] === prev[1]) {
        args.pop()
      } else if (args.length === 1 && args[0] === prev[0]) {
        args = []
      }
      this.activeNode = args
    },
    route(leaf, ...parent) {
      if (this.activeLeaf !== leaf.id) {
        this.activeNode = parent
        this.activeLeaf = leaf.id
        this.$dispatch('on_route', leaf.url)
        session.set('tree_route', this.activeNode.concat(this.activeLeaf))
        session.set('active_url', leaf.url)
      }
    },
    toogleShowMenu() {
      this.isShowMenu = !this.isShowMenu
      session.set('is_show_menu', this.isShowMenu)
    }
  },
  vuex: {
    getters: {
      menuList: state => state.menuList
    },
    actions: {
      xShowMsg: showMsg,
      xGetMenuList: getMenuList
    }
  },
  ready() {
    let treeRoute = session.get('tree_route')
    let active_url = session.get('active_url')
    if (treeRoute) {
      this.activeLeaf = treeRoute.pop()
      this.activeNode = treeRoute
    }
    if(active_url){
      this.$dispatch('on_route', active_url)
    }
    let isShowMenu = true
    if(session.get('is_show_menu')){
      isShowMenu = session.get('is_show_menu')
    }
    
    this.isShowMenu = isShowMenu === undefined ? true : isShowMenu
    this.xGetMenuList().catch(res => {
      this.xShowMsg({
        type: 'danger',
        content: res.error_msg
      })
    })
  }
}
